package com.atgm.mall.gmmailmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atgm.common.constant.MemberConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.exception.MemberException;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.common.utils.R;
import com.atgm.mall.gmmailmember.dao.MemberWishDao;
import com.atgm.mall.gmmailmember.entity.MemberWishEntity;
import com.atgm.mall.gmmailmember.feign.ProductFeignService;
import com.atgm.mall.gmmailmember.feign.vo.GameFeignVo;
import com.atgm.mall.gmmailmember.service.MemberWishService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberWishServiceImpl extends ServiceImpl<MemberWishDao, MemberWishEntity> implements MemberWishService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    @Transactional
    public Long insertMemberWish(MemberWishEntity entity) {
        //TODO 判断会员游戏库中时候含有此游戏
        long id = IdWorker.getId();  //id
        entity.setId(id);
        entity.setDeleted(0);
        entity.setCreateTime(new Date());
        int count = baseMapper.insert(entity);
        if (count < 1) {
            throw new MemberException("添加心愿单失败", BizCodeEnume.ADD_GAME_WISH.getCode());
        }
        //添加到Redis中
        Long memberId = entity.getMemberId();
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        cartOps.put(String.valueOf(id), JSON.toJSONString(entity));

        return id;
    }

    @Override
    @Transactional
    public void deleteWishById(Long id) {
        QueryWrapper<MemberWishEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("member_id");
        queryWrapper.eq("id", id);
        MemberWishEntity memberWishEntity = baseMapper.selectOne(queryWrapper);
        if (memberWishEntity == null) {
            throw new MemberException("删除心愿单失败", BizCodeEnume.DELETE_GAME_WISH.getCode());
        }
        //删除心愿单信息
        int count = baseMapper.deleteById(id);
        if (count < 1) {
            throw new MemberException("删除心愿单失败", BizCodeEnume.DELETE_GAME_WISH.getCode());
        }
        deleteWish(id, memberWishEntity.getMemberId());
    }

    @Override
    @Transactional
    public void deleteWishInfo(Long gameId, Long memberId) {
        QueryWrapper<MemberWishEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("game_id", gameId);
        queryWrapper.eq("member_id", memberId);
        MemberWishEntity memberWishEntity = baseMapper.selectOne(queryWrapper);
        if (memberWishEntity == null) {
            throw new MemberException("删除心愿单失败", BizCodeEnume.DELETE_GAME_WISH.getCode());
        }
        int count = baseMapper.deleteById(memberWishEntity.getId());
        if (count != 1) {
            throw new MemberException("删除心愿单失败", BizCodeEnume.DELETE_GAME_WISH.getCode());
        }
        deleteWish(memberWishEntity.getId(), memberId);
    }

    @Transactional
    public void deleteWish(Long id, Long memberId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        //删除key
        cartOps.delete(id.toString());
        //重新载入
        queryWishGameIds(memberId);
    }

    @Override
    public List<Long> queryWishGameIds(Long memberId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        List<Object> values = cartOps.values();
        if (GmMallUtils.isNotEmpty(values)) {
            List<MemberWishEntity> wishEntityList = values.stream().map(value -> {
                return JSON.parseObject((String) value, MemberWishEntity.class);
            }).collect(Collectors.toList());
            List<Long> ids = wishEntityList.stream().map(MemberWishEntity::getGameId).collect(Collectors.toList());
            return ids;
        }else {
            return null;
        }
    }

    @Override
    public Integer checkIsWished(Long gameId, Long memberId) {
        QueryWrapper<MemberWishEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("game_id", gameId);
        queryWrapper.eq("member_id", memberId);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count;
    }

    /**
     * 获取要操作的redis集合
     * @return
     */
    public BoundHashOperations<String, Object, Object> getCartOps(Long memberId) {
        BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(MemberConstant.WISH_PREFIX + memberId.toString());
        return ops;
    }
}
